package cn.dyp.com.agriculture.util;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.UnknownHostException;

/**
 * 本机Ip获取工具类
 *
 * Created by lenovo on 2017/5/7.
 */

public class IpUtil {
    /**
     * 获取本地Ip
     * context上下文对象
     * @return Ip地址
     */
    public static String getLocalIpAddress(Context context) throws UnknownHostException {
        //获取wifi的信息,需要add [android.permission.ACCESS_WIFI_STATE]
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String IP;
        int ipAddress = wifiInfo.getIpAddress();//获取IP地址
        IP = intToIp(ipAddress);//转换IP地址
        return IP;
    }

    /**
     * 转化Ip
     * i Ip二进制串
     * return 转化后的Ip字符串
     */
    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + ((i >> 24) & 0xFF);
    }

}
